package vn.com.vega.music.clientserver;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import vn.com.vega.music.database.DataStore;
import vn.com.vega.music.objects.Song;
import vn.com.vega.music.utils.Const;
import android.net.Uri;
import android.util.Log;

public class JsonSong extends JsonBase {

	public List<Song> songs;
	public String shareMsg;
	public String shareLink;

	protected JsonSong() {
	}

	public static JsonSong loadListFavoriteSong(int offset) {
		String url = ClientServer.getInstance().getUrlListFavoriteSong(offset);
		return loadSongList(url);
	}
	
	public static JsonSong likeSong(int songId) {
		String url = ClientServer.getInstance().getUrlFavoriteSong(songId);
		JsonSong jsonSong = new JsonSong();
		jsonSong.requestAndParseBasicJson(url);
		return jsonSong;
	}
	
	public static JsonSong unLikeSong(int songId) {
		String url = ClientServer.getInstance().getUrlUnFavoriteSong(songId);
		JsonSong jsonSong = new JsonSong();
		jsonSong.requestAndParseBasicJson(url);
		return jsonSong;
	}

	public static JsonSong loadSongListByAlbumId(int albumId) {
		String url = ClientServer.getInstance().getUrlListSongByAlbum(albumId);
		return loadSongList(url);
	}

	public static JsonSong loadSongListenRecently(int offset) {
		String url = ClientServer.getInstance().getUrlListSongListenRecently(
				offset);
		return loadSongList(url);
	}

	// TuanTM - Add offset parametter
	public static JsonSong loadSongListByPlaylistId(int playlistId/* , int offset */) {
		String url = ClientServer.getInstance().getUrlListSongByPlaylist(
				playlistId/* , offset */);
		return loadSongList(url);
	}

	public static JsonSong loadSongListByArtistId(int artistId, int offset) {
		String url = ClientServer.getInstance().getUrlListSongByArtist(
				artistId, offset);
		return loadSongList(url);
	}

	public static JsonSong loadBillboardSong() {
		String url = ClientServer.getInstance().getUrlBillboardSong();
		return loadSongList(url);
	}

	public static JsonSong loadTopSongList(int offset) {
		return loadTopSongList(offset, Const.LIMIT_ITEM_LOAD_PER_PAGE);
	}

	public static JsonSong loadTopSongList(int offset, int limit) {
		String url = ClientServer.getInstance()
				.getUrlListTopSong(offset, limit);
		return loadSongList(url);
	}

	public static JsonSong search(String keyword, int offset) {
		String url = ClientServer.getInstance().getUrlSearchSong(keyword,
				offset);
		return loadSongList(url);
	}

	public static JsonSong loadSongInfo(int songId) {
		String url = ClientServer.getInstance().getUrlSongInfo(songId);
		return loadSongList(url);
	}

	public static JsonSong shareSong(int songId) {
		String url = ClientServer.getInstance().getUrlShareSong(songId);
		return loadShareContent(url);
	}

	protected static JsonSong loadShareContent(String url) {
		JsonSong result = new JsonSong();
		JSONObject json = result.requestAndParseBasicJson(url);
		if (result.isSuccess()) {
			try {

				JSONObject aData = json.getJSONObject("data");

				result.shareMsg = aData.getString("message");
				result.shareLink = aData.getString("link");

			} catch (Exception ex) {
				result.setParsingError();
			}
		}
		return result;
	}

	protected static JsonSong loadSongList(String url) {
		JsonSong result = new JsonSong();
		JSONObject json = result.requestAndParseBasicJson(url);
		if (result.isSuccess()) {
			try {
				result.parseSongList(json);
			} catch (Exception ex) {
				result.setParsingError();
			}
		}
		return result;
	}

	public void parseSongList(JSONObject json) throws JSONException {
		// channel category
		ArrayList<Song> detailSongs = new ArrayList<Song>();
		JSONArray aData = json.getJSONArray("data");
		for (int i = 0; i < aData.length(); i++) {
			JSONObject obj = aData.getJSONObject(i);
			Song v = parseSong(obj);
			detailSongs.add(v);
		}
		songs = detailSongs;
	}

	/**
	 * 
	 * Music quality list
	 * */
	public static JsonSong loadMusicQualityList() {
		JsonSong result = new JsonSong();
		String url = ClientServer.getInstance().getUrlListAudioProfile();
		Log.i("URL", url);
		JSONObject json = result.requestAndParseBasicJson(url);

		if (result.isSuccess()) {
			try {
				result.parseMusicQualityList(json);
			} catch (Exception ex) {
				result.setParsingError();
			}
		}

		return result;
	}

	public void parseMusicQualityList(JSONObject json) throws JSONException {
		// channel category
		ArrayList<Song> detailSongs = new ArrayList<Song>();
		JSONArray aData = json.getJSONArray("data");
		for (int i = 0; i < aData.length(); i++) {
			JSONObject obj = aData.getJSONObject(i);
			Song v = parseMusicQuality(obj);
			detailSongs.add(v);
		}
		songs = detailSongs;
	}

	private Song parseMusicQuality(JSONObject obj) {
		Song s = new Song(Song.SONG_TYPE_SERVER);
		try {
			s.id = obj.getInt("id");
			s.title = obj.getString("name");
		} catch (Throwable t) {
			setParsingError();
		}
		return s;
	}

	public static Uri loadSongUri(Song song) {
		String path = null;
		if (song == null) {
			return null;
		}

		if (song.isLocalSong() || song.isAvailableLocally()) {
			path = song.cached_file_path;
		} else {
			if (song.isAvailableLocally()) {
				// Get stored song path
				path = song.cached_file_path;
			} else {
				// Get song path from server
				String audioProfileId = DataStore.getInstance().getConfig(
						Const.MUSIC_QUALITY_ID);
				JsonListenUrl _jresult = JsonListenUrl.loadListenUrl(song.id,
						audioProfileId);
				if (_jresult.getErrorCode() == 0) {
					path = _jresult.listenUrl;
				} else {
					path = null;
				}
			}
		}
		if (path != null) {
			// Some time server return beta
			Uri uri = Uri.parse(path);
			String hostBeta = uri.getHost();
			if (hostBeta != null) {
				String hostReal = hostBeta.replace("beta.", "");
				path = path.replaceAll(hostBeta, hostReal);
			}
			return Uri.parse(path);
		} else {
			return null;
		}
	}

	public static String loadLyric(Song song) {
		try {
			String urlLyric = ClientServer.getInstance().getUrlSongLyrics(
					song.id);
			JsonSong jsonSong = new JsonSong();
			JSONObject jsonObject = jsonSong.requestAndParseBasicJson(urlLyric);
			if (jsonSong.isSuccess()) {
				// TODO:
				JSONArray data = jsonObject.getJSONArray("data");
				JSONObject object = (JSONObject) data.get(0);
				String lyric = object.getString("lyric");
				return lyric;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}
}
